package controller

import (
	"GoAdmin/common"
	"GoAdmin/models"
	"GoAdmin/utils"
	"crypto/md5"
	"encoding/hex"
	"github.com/astaxie/beego/validation"
	"github.com/spf13/cast"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
	"xorm.io/builder"

	"github.com/gin-gonic/gin"
)

// GetRoleList 获取角色列表
func GetRoleList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "15"))
	offset := (page - 1) * pageSize
	count, list, _ := new(models.OaRole).GetAllRoleList(pageSize, offset)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "查询成功", "data": gin.H{"list": list, "count": count}})
	// return
}

// GetRoleUserList 获取用户列表
func GetRoleUserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "15"))
	offset := (page - 1) * pageSize
	count, list, _ := new(models.OaUserRole).GetUserRoleList(pageSize, offset)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "查询成功", "data": gin.H{"list": list, "count": count}})
	// return
}

// AddRole 添加角色
func AddRole(c *gin.Context) {
	var (
		oaRole models.OaRole
	)
	//获取参数
	valid := validation.Validation{}
	valid.Required(c.PostForm("name"), "name").Message("角色名称不能为空")
	valid.Required(c.PostForm("description"), "description").Message("角色描述不能为空")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	user, _ := common.GetCtxUser(c)
	oaRole.RoleAction = ""
	oaRole.CreatorId = user.Id
	oaRole.Name = c.PostForm("name")
	oaRole.Status = "1"
	oaRole.Description = c.PostForm("description")
	oaRole.CreateTime = time.Now()
	if !oaRole.Add() {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "添加失败"})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "添加成功"})
	}
}

func DelUserRole(c *gin.Context) {
	valid := validation.Validation{}
	valid.Required(c.PostForm("id"), "id").Message("该角色未找到")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	ok, or, err := new(models.OaRole).GetById(c.PostForm("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误"})
		return
	} else if !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该角色不存在"})
		return
	}
	or.Status = "0"
	or.EditTime = time.Now().Format("2006-01-02 15:04:05")
	if !or.Edit("status", "edit_time") {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除成功"})
	return
}

// EditRole 修改角色姓名描述
func EditRole(c *gin.Context) {
	//获取参数
	valid := validation.Validation{}
	valid.Required(c.PostForm("id"), "id").Message("记录未找到")
	valid.Required(c.PostForm("name"), "name").Message("角色名称不能为空")
	valid.Required(c.PostForm("description"), "description").Message("角色描述不能为空")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	ok, or, err := new(models.OaRole).GetById(c.PostForm("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误"})
		return
	} else if !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该角色不存在"})
		return
	}
	or.Name = c.PostForm("name")
	or.Description = c.PostForm("description")
	if c.PostForm("role") != "" {
		or.RoleAction = c.PostForm("role")
	}
	if !or.Edit("name", "description", "role_action") {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "角色更新失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "角色更新成功"})
}

func GetUserMenu(c *gin.Context) {

	user, _ := common.GetCtxUser(c)
	log.Println(user.Id, user.Name)
	userRole, err := new(models.OaUserRole).GetUserRoleByUserId(user.Id)
	if err != nil {
		return
	}
	//return
	// 查询用户权限
	list, err := new(models.OaPrivilege).GetById()
	if err != nil {
		log.Println(err)
	}
	// 整理权限菜单
	var firstMenu []map[string]interface{}
	var secondMenu []map[string]interface{}
	var roleMenu []map[string]interface{}
	log.Println(userRole.RoleAction)
	for _, v := range list {
		menu := map[string]interface{}{}
		if utils.SliceContains(strings.Split(userRole.RoleAction, ","), cast.ToString(v.Id)) {
			menu["checked"] = "1"
		} else {
			menu["checked"] = "0"
		}
		menu["title"] = v.Name
		menu["id"] = v.Id
		menu["parent_id"] = v.Pid
		menu["index"] = v.Index
		menu["icon"] = v.Icon
		// 所有的权限
		if v.Cate == 1 && menu["checked"] == "1" {
			firstMenu = append(firstMenu, menu)
		}
		if v.Cate == 2 && menu["checked"] == "1" {
			secondMenu = append(secondMenu, menu)
		}
		if v.Cate == 3 && menu["checked"] == "1" {
			roleMenu = append(roleMenu, menu)
		}
	}
	for _, k := range secondMenu {
		var role []map[string]interface{}
		for _, v := range roleMenu {
			if k["id"] == v["parent_id"] {
				role = append(role, v)
			}
		}
		k["subs"] = role
	}
	for _, k := range firstMenu {
		var role []map[string]interface{}
		for _, v := range secondMenu {
			if k["id"] == v["parent_id"] {
				role = append(role, v)
			}
		}
		k["subs"] = role
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "ok", "data": firstMenu})
	return

}

// GetUserRole 获取角色的权限
func GetUserRole(c *gin.Context) {
	id := c.Query("id")
	valid := validation.Validation{}
	valid.Required(id, "id").Message("未选择角色")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}

	userRole, err := new(models.OaUserRole).GetUserRoleByRoleId(id)
	if err != nil {
		return
	}
	//return
	// 查询用户权限
	list, err := new(models.OaPrivilege).GetById()
	if err != nil {
		log.Println(err)
	}
	// 整理权限菜单
	var firstMenu []map[string]interface{}
	var secondMenu []map[string]interface{}
	var roleMenu []map[string]interface{}
	for _, v := range list {
		//log.Println(v)
		menu := map[string]interface{}{}
		if strings.Contains(userRole.RoleAction, cast.ToString(v.Id)) {
			menu["checked"] = "1"
		} else {
			menu["checked"] = "0"
		}
		menu["title"] = v.Name
		menu["id"] = v.Id
		menu["parent_id"] = v.Pid
		// 所有的权限
		if v.Cate == 1 {
			firstMenu = append(firstMenu, menu)
		}
		if v.Cate == 2 {
			secondMenu = append(secondMenu, menu)
		}
		if v.Cate == 3 {
			roleMenu = append(roleMenu, menu)
		}
	}
	for _, k := range secondMenu {
		var role []map[string]interface{}
		for _, v := range roleMenu {
			if k["id"] == v["parent_id"] {
				role = append(role, v)
			}
		}
		k["subs"] = role
	}
	for _, k := range firstMenu {
		var role []map[string]interface{}
		for _, v := range secondMenu {
			if k["id"] == v["parent_id"] {
				role = append(role, v)
			}
		}
		k["subs"] = role
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "ok", "data": firstMenu})
	return

}

// SetUserRole 保存角色的权限
func SetUserRole(c *gin.Context) {
	var (
		id   string
		role models.OaRole
		has  bool
	)
	id = c.PostForm("id")
	valid := validation.Validation{}
	valid.Required(id, "id").Message("未选择角色")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}

	if has, role, _ = new(models.OaRole).GetById(id); !has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该角色不存在"})
		return
	}
	role.RoleAction = strings.Join(c.PostFormArray("role_id"), ",")
	role.EditTime = time.Now().Format("2006-01-02 15:04:05")
	role.Edit("role_action", "edit_time")
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "权限保存成功"})
	return
}

func GetAllRoleList(c *gin.Context) {
	var (
		user *models.OaUser
		ok   bool
	)
	if user, ok = common.GetCtxUser(c); !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "用户信息验证失败"})
		return
	}
	userRole, err := new(models.OaUserRole).GetUserRoleByUserId(user.Id)
	if err != nil {
		return
	}
	// 查询用户权限
	list, err := new(models.OaMenu).GetUserRoleList()
	if err != nil {
		log.Println(err)
	}
	// 整理权限菜单
	var firstMenu []map[string]interface{}
	var secondMenu []map[string]interface{}
	var roleMenu []map[string]interface{}
	for _, v := range list {
		//log.Println(v)
		menu := map[string]interface{}{}
		if strings.Contains(userRole.RoleAction, cast.ToString(v.Id)) {
			menu["checked"] = "1"
		} else {
			menu["checked"] = "0"
		}
		menu["title"] = v.Title
		menu["id"] = v.Id
		menu["parent_id"] = v.ParentId
		// 所有的权限
		if v.Cate == 1 {
			firstMenu = append(firstMenu, menu)
		}
		if v.Cate == 2 {
			secondMenu = append(secondMenu, menu)
		}
		if v.Cate == 3 {
			roleMenu = append(roleMenu, menu)
		}
	}
	for _, k := range secondMenu {
		var role []map[string]interface{}
		for _, v := range roleMenu {
			if k["id"] == v["parent_id"] {
				role = append(role, v)
			}
		}
		k["subs"] = role
	}
	for _, k := range firstMenu {
		var role []map[string]interface{}
		for _, v := range secondMenu {
			if k["id"] == v["parent_id"] {
				role = append(role, v)
			}
		}
		k["subs"] = role
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "ok", "data": firstMenu})
	return
}

func AddRoleUser(c *gin.Context) {
	var (
		name     string
		role_id  string
		oAuser   models.OaUser
		has      bool
		userrole models.OaUserRole
	)
	user, _ := common.GetCtxUser(c)
	role_id = c.PostForm("role_id")
	name = c.PostForm("name")
	valid := validation.Validation{}
	valid.Required(role_id, "role_id").Message("未选择角色")
	valid.Required(name, "name").Message("未输入名字")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	h := md5.New()
	h.Write([]byte(c.PostForm("password")))
	oAuser.Name = c.PostForm("name")
	oAuser.Type = "4"
	oAuser.Password = hex.EncodeToString(h.Sum(nil))
	namefilter := builder.NewCond().And(builder.Eq{"name": oAuser.Name})
	if has, _, _ = new(models.OaUser).GetUserExist(namefilter); has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该账号/姓名重复"})
		return
	}
	if !oAuser.Add() {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "插入用户失败"})
		return
	}
	userrole.UserId = oAuser.Id
	role_id = c.PostForm("role_id")
	userrole.RoleId, _ = strconv.Atoi(role_id)
	userrole.CreatorId = user.Id
	userrole.AddTime = time.Now()
	if !userrole.Add() {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "插入用户失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "添加成功"})
	return
}

func EditRoleUser(c *gin.Context) {
	var (
		user_id string
		user    models.OaUser
		name    string
		has     bool
	)
	if user_id = c.PostForm("user_id"); user_id == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误"})
		return
	}
	user, _ = new(models.OaUser).GetByUser(user_id)
	name = c.PostForm("name")
	if name == user.Name {

	} else {
		filter := builder.NewCond()
		filter = filter.And(builder.Eq{"name": name})
		if has, _, _ = new(models.OaUser).GetUserExist(filter); has {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该账号/姓名重复"})
			return
		}
	}
	password := c.PostForm("password")
	user.Password = utils.Md5(password)
	user.Name = name
	if !user.Edit("name", "password") {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "更新失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "用户更新成功"})
	return
}
